package com.diorsunion.hedge.bo.net;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.diorsunion.hedge.constant.Constants;
import com.diorsunion.hedge.enums.Period;
import com.diorsunion.hedge.dal.entity.stock.Stock;
import com.diorsunion.hedge.dal.entity.stock.StockPrice;
import com.diorsunion.hedge.util.LogUtil;
import com.google.common.collect.Lists;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by harley-dog<custer7572@163.com> on 15/12/15.
 */
@Service("XueQiuDataFetcher")
public class XueQiuDataFetcher implements DataFetcher {

    @Value("${xueqiu.url.stockprice}")
    String xueqiu_url_stockprice;

    /*TODO cookie这个东西，还是得搞个简单的缓存啊，一天刷新一次就可以了哦*/
    private long time = 0 ;
    private String cookie_cached ;

    @Override
    public List<StockPrice> fetchStockPrice(Stock stock, Date begin, Date end, Period period) throws IOException, URISyntaxException, ParseException {
        DateFormat dateFormat_US = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
        DateFormat dateFormat_CN = new SimpleDateFormat("yyyy-MM-dd");
        LogUtil.debug("fetchStockPrice,stock:" + stock.code + ",begin:" + dateFormat_CN.format(begin) + ",end:" + dateFormat_CN.format(end) + ",peroid:" + period);
        URIBuilder uriBuilder = new URIBuilder(xueqiu_url_stockprice)
                .setParameter("type", "normal")
                .setParameter("_", String.valueOf(System.currentTimeMillis()))
                .setParameter("begin", String.valueOf(begin.getTime()))
                .setParameter("end", String.valueOf(end.getTime()))
                .setParameter("period", getPeroidParam(period))
                .setParameter("symbol", stock.code);
        URI uri = uriBuilder.build();
        URL url = uri.toURL();
        URI root_uri = new URI("http://" + uri.getHost());
        String cookie = getCookie(root_uri);
//        String cookie ="s=1wfu11fyav; xq_a_token=934f674c5167ef0a40bc92c387554e5b8d74a6f8; xq_r_token=ed5549c6fd48ab1fbe3f40b00a823b21dbd4f618; __utmt=1; Hm_lvt_1db88642e346389874251b5a1eded6e3=1464084368,1464089228,1464336044,1464591094; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1464591099; __utma=1.806431414.1463986343.1464351073.1464591095.11; __utmb=1.2.10.1464591095; __utmc=1; __utmz=1.1463986343.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)";
        HttpGet httpget = new HttpGet(uri);
        httpget.addHeader("Cookie", cookie);
        httpget.addHeader("Host", "xueqiu.com");
//        httpget.addHeader("RA-Sid", "3CB01D6F-20140709-112055-4c09cf-c1239f");
        httpget.addHeader("Upgrade-Insecure-Requests", "1");
        httpget.addHeader("Connection", "keep-alive");
        httpget.addHeader("X-Whom", "hzali-ngx-228-73");
//        httpget.addHeader("Transfer-Encoding","chunked");
        httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
        httpget.addHeader("Accept-Language","Accept-Language:zh-CN,zh;q=0.8,en;q=0.6");
        httpget.addHeader("Cache-Control","max-age=0");
        LogUtil.info("Executing request " + httpget.getRequestLine());
        CloseableHttpClient httpclient = HttpClients.custom().build();
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity);
        response.close();
        httpclient.close();
        JSONObject obj = JSON.parseObject(s);
        JSONArray chartlist = (JSONArray) obj.get("chartlist");
        List<StockPrice> stockPrices = Lists.newArrayList();
        if (chartlist == null) {
            LogUtil.info(LogUtil.net, "抓取雪球网数据失败,url:" + url.toString() + ",result is:" + s);
        }
        for (int i = 0; chartlist != null && i < chartlist.size(); i++) {
            StockPrice stockPrice = new StockPrice();
            JSONObject jsonObject = chartlist.getJSONObject(i);
            JSONObject preObject = null;
            JSONObject nextObject = null;
            if (i > 0) {
                preObject = chartlist.getJSONObject(i - 1);
            }
            if (i < chartlist.size() - 1) {
                nextObject = chartlist.getJSONObject(i + 1);
            }
            stockPrice.chg = Double.parseDouble(jsonObject.get("chg").toString());
            stockPrice.close = Double.parseDouble(jsonObject.get("close").toString());
            stockPrice.dea = Double.parseDouble(jsonObject.get("dea").toString());
            stockPrice.dif = Double.parseDouble(jsonObject.get("dif").toString());
            stockPrice.high = Double.parseDouble(jsonObject.get("high").toString());
            stockPrice.low = Double.parseDouble(jsonObject.get("low").toString());
            stockPrice.ma10 = Double.parseDouble(jsonObject.get("ma10").toString());
            stockPrice.ma20 = Double.parseDouble(jsonObject.get("ma20").toString());
            stockPrice.ma30 = Double.parseDouble(jsonObject.get("ma30").toString());
            stockPrice.ma5 = Double.parseDouble(jsonObject.get("ma5").toString());
            stockPrice.macd = Double.parseDouble(jsonObject.get("macd").toString());
            stockPrice.open = Double.parseDouble(jsonObject.get("open").toString());
            stockPrice.percent = Double.parseDouble(jsonObject.get("chg").toString());
            stockPrice.volume = new BigDecimal(jsonObject.get("volume").toString()).longValue();
            stockPrice.stock = stock;
            stockPrice.turnrate = Double.parseDouble(jsonObject.get("turnrate").toString());
            stockPrice.thedate = dateFormat_US.parse(jsonObject.get("time").toString());
            stockPrice.preDate = (i == 0 && begin.getTime() != Constants.date20100101.getTime()) ? begin : preObject != null ? dateFormat_US.parse(preObject.get("time").toString()) : null;
            stockPrice.nextDate = nextObject != null ? dateFormat_US.parse(nextObject.get("time").toString()) : null;
            stockPrices.add(stockPrice);
        }
        return stockPrices;
    }

    private String getPeroidParam(Period period) {
        switch (period) {
            case day:
                return "1day";
            case week:
                return "1week";
            case month:
                return "1month";
            default:
                return "1day";
        }
    }

}
